//
//  Reachability.swift
//  BaoKeSwift
//
//  Created by duan on 15/10/2017.
//  Copyright © 2017 geek-duan. All rights reserved.
//

import Foundation

class ReachabilityHelper {
    /// - 单例
    static let shard = ReachabilityHelper()
    /// - 监测实例
    let reachability = Reachability()!
    /// - 连接网络类型
    var networkStatus: Reachability.Connection = .none
    
    // MARK: - 实时监测网络状态
    func startNotifierNotworkStatus() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(_:)), name: .reachabilityChanged, object: reachability)
        do{
            try reachability.startNotifier()
        }catch{
            print("could not start reachability notifier")
        }
    }
    
    // MARK: - 网络状态改变通知
    @objc func reachabilityChanged(_ note: Notification) {
        
        let reachability = note.object as! Reachability
        
        switch reachability.connection {
        case .wifi:
            print("Reachable via WiFi")
            networkStatus = .wifi
        case .cellular:
            print("Reachable via Cellular")
            networkStatus = .cellular
        case .none:
            print("Network not reachable")
            networkStatus = .none
        }
    }
    
    // MARK: - 移除通知
    deinit {
        
        reachability.stopNotifier()
        NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
    }
}
